import api from "../../utils/api_util";
import tips from "../../utils/tip";
import baseUtil from "../../utils/base_util";

const app = getApp();
Page({
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        HasBingAddress: true,
        isDelete: false,
        isEdit: false,
        AddressList: [],
        //收货
        area: ['北京市', '北京市', '东城区'],
        areaCode: [],
        phone: '',
        addressId: -1,
        shopDetailData: '',
        totalPrice: '',
        //积分
        items: [
            {name: true, value: '使用积分', checked: 'true'},
            {name: false, value: '不使用', checked: 'false'},
        ],
        integral: 'false',
        jifenNumber: '',
        userIntegral: '',
        goodsIntegral: 56,
    },
    onShow: function () {
        this.getUserAddress();
        this.getShopDetail();
        this.getAccount();
    },
    onLoad: function (options) {

    },
    setDefaultAddress() {
        // let DefaultAddress = this.data.AddressList.find(item => item.acquiescence == true);
        // if (typeof DefaultAddress == 'undefined') {
        //     wx.showToast({
        //         title: "您还没有选择默认的地址",
        //         icon: "none"
        //     })
        //     return
        // } else {
        this.setData({
            // defaultaddress: DefaultAddress.address,
            // defaultname: DefaultAddress.name,
            // defaultphone: DefaultAddress.phone,
            // defaultarea: DefaultAddress.area.join(''),
            AddressListModal: null,
            isDelete: false,
            // })
            // wx.showToast({
            //     title: "地址：" + DefaultAddress.area.join('') + DefaultAddress.address + "已经设置为默认地址",
            //     icon: "none"
            // })
        })

    },
    // showModal: function(e) {
    //   var showName = e.currentTarget.dataset.modal;
    //   this.setData({
    //     modalName: showName
    //   })
    // },
    closeModal: function (e) {
        this.setData({
            modalName: null
        })
    },
    closeAddressModal() {
        this.setData({
            addAddressModal: null,
            address: '',
            name: '',
            phone: '',
            // area: ["北京市", "北京市", "东城区"]
        })
    },
    newAddAddress() {
        this.setData({
            isEdit: false,
            addAddressModal: "addAddressModal"

        })
    },
    closeAddressListModal() {
        this.setData({
            AddressListModal: null,
            isDelete: false
        })
    },
    showAddressModal(e) {
        this.data.AddressList == 0 ? this.setData({
            isEdit: false,
            addAddressModal: "addAddressModal"
        }) : this.setData({
            isEdit: true,
            AddressListModal: "AddressListModal"
        })
    },
    showDeleteAddress() {
        let AddressList = this.data.AddressList;
        this.setData({
            isDelete: !this.data.isDelete,
            AddressList
        })
    },

    /**
     * 地址
     */
    //获取收货地址
    getUserAddress: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.addressList, {
            method: 'GET',
            data: {
                v: '1.0.0',
            },
            success: function (res) {
                res.data.rows.forEach(item => {
                    if (item.acquiescence == 'false') {
                        item.acquiescence = false;
                    } else {
                        item.acquiescence = true;
                        that.data.addressId = item.id;
                    }
                })
                let DefaultAddress = res.data.rows.filter(item => item.acquiescence == true);

                that.setData({
                    AddressList: res.data.rows,
                    defaultaddress: DefaultAddress[0].address,
                    defaultname: DefaultAddress[0].name,
                    defaultphone: DefaultAddress[0].mobile,
                    defaultarea: DefaultAddress[0].regionName,
                    addressId: that.data.addressId
                })
                console.log('寄货地址:', that.data.addressId)
            },
        })
    },
    // 确认修改原地址
    editAddress(e) {
        let that = this;

        api.wxRequest.apiRequest(that, api.urls.updataAddress, {
            method: 'POST',
            data: {
                v: '1.0.0',
                name: that.data.name,
                mobile: that.data.phone,
                address: that.data.address,
                provinceId: that.data.areaCode[0],
                cityId: that.data.areaCode[1],
                districtId: that.data.areaCode[2],
                id: that.data.updataId,
            },
            success: function (res) {

                that.setData({
                    AddressListModal: "AddressListModal",
                });

                that.getUserAddress();
                that.closeAddressModal();
            },
        })


    },
    // 选择默认地址
    radioChange(e) {
        let that = this;
        console.log(e.detail.value);
        api.wxRequest.apiRequest(that, api.urls.modifyAcquiescence, {
            method: 'POSt',
            data: {
                v: '1.0.0',
                id: e.detail.value,
            },
            success: function (res) {
                that.getUserAddress();
            },
        })
    },
    // 编辑地址，实际跟 添加地址用的同一个模态框
    editAddressModel(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;

        console.log('地址详情:', id);
        api.wxRequest.apiRequest(that, api.urls.detailsAddress, {
            method: 'GET',
            data: {
                v: '1.0.0',
                id: id,
            },
            success: function (res) {
                let AddressList = that.data.AddressList.find(item => item.id == id);
                // console.log(AddressList);
                that.data.areaCode[0] = res.data.provinceId;
                that.data.areaCode[1] = res.data.cityId;
                that.data.areaCode[2] = res.data.districtId;
                that.data.region = res.data.regionName;
                that.setData({
                    editaddressid: res.data.id,
                    name: res.data.name,
                    phone: res.data.mobile,
                    areaCode: that.data.areaCode,
                    area: res.data.regionName.split(','),
                    region: that.data.region,
                    address: AddressList.address,
                    addAddressModal: "addAddressModal",
                    isEdit: true,
                    updataId: id,
                })
            },
        })

    },
    // 删除地址按钮
    deleteAddress(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定删除收货地址吗？',
            success(res) {
                if (res.confirm) {
                    api.wxRequest.apiRequest(that, api.urls.deleteAddress, {
                        method: 'POST',
                        data: {
                            v: '1.0.0',
                            id: id,
                        },
                        success: function (res) {
                            that.getUserAddress();
                        },
                    })
                } else if (res.cancel) {
                }
            }
        })
    },
    // 三级地理位置连锁
    bindRegionChange: function (e) {
        console.log('地址：', e.detail.value);
        console.log('地址code：', e.detail.code);
        this.setData({
            area: e.detail.value,
            areaCode: e.detail.code
        })
    },
    // 收货人名
    watchName(e) {
        this.setData({
            name: e.detail.value
        })
    },
    // 收货手机号
    watchPhone(e) {
        this.setData({
            phone: e.detail.value
        })
    },
    // 地址
    watchAddress(e) {
        this.setData({
            address: e.detail.value
        })
    },
    // 添加地址
    AddAddress() {
        let that = this;
        if (this.data.name && this.data.phone && this.data.address) {
            let area = this.data.area;
            let address = this.data.address;
            let name = this.data.name;
            let phone = this.data.phone;

            api.wxRequest.apiRequest(that, api.urls.createAddress, {
                method: 'POST',
                data: {
                    v: '1.0.0',
                    name: name,
                    mobile: phone,
                    address: address,
                    provinceId: that.data.areaCode[0],
                    cityId: that.data.areaCode[1],
                    districtId: that.data.areaCode[2],
                },
                success: function (res) {
                    that.setData({
                        // AddressList,
                        addAddressModal: null,
                        AddressListModal: "AddressListModal",
                        // address: '',
                        // name: '',
                        // phone: '',
                        // region: ["北京市", "北京市", "东城区"]
                    });
                    that.getUserAddress();
                },
            })
        } else {
            wx.showToast({
                title: '请填写完整',
                icon: "none"
            })
        }

    },
    /**
     * 下单
     */
    //商品详情
    getShopDetail() {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.goosDetail, {
            method: 'GET',
            data: {
                id: baseUtil.getCurrentUrlParam('goodsId'),
            },
            success: function (res) {

                that.data.totalPrice = baseUtil.getCurrentUrlParam('quantity') * res.data.currentPrice;
                that.data.goodsIntegral = baseUtil.getCurrentUrlParam('quantity') * res.data.integral;
                that.setData({
                    shopDetailData: res.data,
                    quantity: baseUtil.getCurrentUrlParam('quantity'),
                    totalPrice: that.data.totalPrice,
                    goodsIntegral: that.data.goodsIntegral,
                })
            },
        })
    },
    //是否积分
    radioIntegral: function (e) {

        let that = this;

        this.data.integral = e.detail.value;
        this.setData({
            integral: that.data.integral
        });
    },
    jifenInput: function (e) {
        if (e.detail.value > this.data.goodsIntegral) {
            tips.alert('不能超过商品最高抵扣积分哦~')
        }
        this.setData({
            jifenNumber: e.detail.value,
        })
    },
    //创建订单
    createOrderPost: function () {
        let that = this;
        if (that.data.jifenNumber > that.data.goodsIntegral) {
            tips.alert('积分不足~');

            return;
        }
        if (that.data.addressId < 0) {
            tips.alert('请选地址~');

            return;

        }
        // if (that.data.jifenNumber > that.data.userIntegral) {
        //     tips.alert('不能超过已有积分哦~');
        // }
        api.wxRequest.apiRequest(that, api.urls.creatOrder, {
            method: 'POST',
            data: {
                goodsId: baseUtil.getCurrentUrlParam('goodsId'),
                quantity: baseUtil.getCurrentUrlParam('quantity'),
                shippingAddressId: that.data.addressId,
                deduction: that.data.integral,
                integrals: that.data.jifenNumber,
            },
            success: function (res) {
                that.wxPay(res.data);
            },
        })


    },

    //微信支付
    wxPay: function (data) {
        let that = this;
        let ntr = Math.random().toString(36).substr(2);

        api.wxRequest.apiRequest(that, api.urls.wxPay, {
            method: 'POST',
            data: {
                nonceStr: ntr, //随机数
                signature: '56135Xfsdk', //签名
                orderId: data.orderId,
                payChannels: "weixinPay",
                integral: (data.totalIntegrals ? data.totalIntegrals : 0),
                price: data.totalPrice,
                v: '1.0.0'
            },
            success: function (res) {
                console.log('支付信息：', res);

                wx.requestPayment({
                    'timeStamp': (res.data.timeStamp).toString(),
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.sign,
                    success: function (res) {
                        baseUtil.pageJump('/pages/OrderDetail/OrderDetail?orderId=' + data.orderId)
                    },
                    fail: function (res) {
                        tips.alert('支付已取消');
                        console.log('支付错误信息:', res)
                    }
                })

            },
        })

    },
    //获取用户积分
    getAccount: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.myAccount, {
            method: 'GET',
            data: {
                v: '1.0.0',
            },
            success: function (res) {
                that.setData({
                    userIntegral: res.data.usableIntegral,
                })
            },
        })
    },

})